<!-- 产品发布 - 库存价格 -->
<template>
  <el-form
    ref="formRef"
    v-loading="formLoading"
    :disabled="props.isDetail"
    :model="formData"
    :rules="rules"
    label-width="80px"
  >
    <el-form-item label="积分抵扣" prop="isIntegral">
      <el-radio-group v-model="formData!.isIntegral">
        <el-radio :value="false">关闭</el-radio>
        <el-radio :value="true">开启</el-radio>
      </el-radio-group>
      <el-text class="w-full" size="small" type="info">
        {{
          formData!.isIntegral
            ? '下单时可以使用积分抵扣，需要填写成本价。积分价格由“(销售价-成本价)/积分现金价值”得出。'
            : '下单时不能使用积分抵扣。'
        }}
      </el-text>
    </el-form-item>
    <!-- <el-form-item label="联盟豆抵扣" prop="isCryptocurrency">
      <el-radio-group v-model="formData.isCryptocurrency">
        <el-radio :label="false">关闭</el-radio>
        <el-radio :label="true">开启</el-radio>
      </el-radio-group>
      <el-text class="w-full" size="small" type="info">
        {{
          formData.isCryptocurrency
            ? '下单时可以使用联盟豆抵扣。联盟豆价格由“(销售价-成本价)/联盟豆现金价值”得出，成本低于5折的则支持联盟豆全额兑换。'
            : '下单时不能使用联盟豆抵扣。'
        }}
      </el-text>
    </el-form-item> -->
    <!-- <el-form-item v-if="formData.isIntegral" label="转赠积分" prop="giveIntegral">
      <el-input-number
        v-model="formData.giveIntegral"
        :min="0"
        placeholder="请输入转赠积分"
        class="w-80!"
      />
      <el-text class="w-full" size="small" type="info">
        消费者购买成功后获得商家转赠的积分，0 表示以平台设置的为准（TODO 前期先不让商家设置，后续再考虑平台如何给商家开通权限）
      </el-text>
    </el-form-item> -->
    <!-- <el-form-item label="分佣产品" prop="isBrokerage">
      <el-radio-group v-model="formData.isBrokerage" @change="changeBrokerage">
        <el-radio :label="false">不分佣</el-radio>
        <el-radio :label="true" class="radio">分佣</el-radio>
      </el-radio-group>
    </el-form-item> -->
    <el-form-item label="计价模式" prop="priceMode" :title="formData!.type">
      <div class="flex flex-col">
        <el-radio-group v-model="formData!.priceMode" @change="onPriceModeChange">
          <el-radio
            v-for="(item, index) in priceModeMap"
            :key="index"
            :value="Number(index)"
            :disabled="formData!.type !== 'food' && Number(index) === 2"
          >
            {{ item }}
          </el-radio>
        </el-radio-group>
        <el-text v-if="formData!.priceMode === 1" type="info">
          按单品计价，单品的相关价格必须填写，设置为 0 表示免费
        </el-text>
        <el-text v-else-if="formData!.priceMode === 2" type="info">
          按称重计价，单价由全局配置的荤菜单价及素菜单价自动计算得来
        </el-text>
      </div>
    </el-form-item>
    <el-form-item v-if="formData!.priceMode === 2" label="计价单位" prop="unitName">
      <el-radio-group v-model="formData!.unitName">
        <el-radio v-for="item in weightUnitMap" :key="item" :value="item" :disabled="item === '两'">
          {{ item }}
        </el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item v-else label="计价单位" prop="unitName">
      <div class="flex flex-col">
        <el-input
          v-model="formData!.unitName"
          :clearable="true"
          class="!w-100px !md-w-180px"
          placeholder="计价单位，如：件、份"
        />
      </div>
    </el-form-item>
    <el-form-item label="计价数值" prop="stepQuantity">
      <div class="flex flex-col">
        <el-input-number
          v-model="formData!.stepQuantity"
          :min="0"
          :max="99999999"
          :step="1"
          controls-position="right"
          placeholder="计价数值"
          class="!w-100px !md-w-180px"
          @change="onStepQuantityChange"
        >
          <template #suffix>
            <span>{{ formData!.unitName || '' }}</span>
          </template>
        </el-input-number>
        <el-text type="info"> 每次加购的数量，用于计算价格，如：1件、50克</el-text>
      </div>
    </el-form-item>
    <el-form-item label="产品规格" prop="specType">
      <el-radio-group
        v-model="formData!.specType"
        class="w-80"
        @change="onChangeSpec"
        :disabled="Boolean(formData!.id)"
      >
        <el-radio :value="false" class="radio">单规格</el-radio>
        <el-radio :value="true">多规格（如：颜色+尺码）</el-radio>
      </el-radio-group>
    </el-form-item>
    <!-- 多规格添加-->
    <el-form-item v-if="!formData!.specType" label-width="1px">
      <SkuList
        ref="skuListRef"
        :prop-form-data="formData"
        :property-list="propertyList"
        :rule-config="ruleConfig"
      />
    </el-form-item>
    <el-form-item v-if="formData!.specType" label="" label-width="20px">
      <div class="flex flex-col">
        <div v-if="!formData!.id" class="flex flex-row items-center mb-5px">
          <el-button @click="attributesAddFormRef.open" type="primary" :plain="true" size="small"
            >添加规格条目
          </el-button>
          <span class="ml-10px text-gray-400">如“颜色”“尺码”等</span>
        </div>
        <ProductAttributes
          :property-list="propertyList"
          @success="generateSkus"
          :is-detail="props.isDetail || Boolean(formData!.id)"
        />
      </div>
    </el-form-item>
    <template v-if="formData!.specType && propertyList.length > 0">
      <el-form-item v-if="!props.isDetail" label="" label-width="20px">
        <el-button type="success" :plain="true" @click="showBatchSetting = !showBatchSetting"
          >{{ showBatchSetting ? '关闭批量设置' : '打开批量设置' }}
        </el-button>
        <SkuList
          v-if="showBatchSetting"
          :is-batch="true"
          :prop-form-data="formData"
          :property-list="propertyList"
        />
      </el-form-item>
      <el-form-item label="" label-width="20px">
        <SkuList
          ref="skuListRef"
          :is-detail="props.isDetail"
          :prop-form-data="formData"
          :property-list="propertyList"
          :rule-config="ruleConfig"
        />
      </el-form-item>
    </template>
  </el-form>

  <!-- 产品规格添加 Form 表单 -->
  <ProductPropertyAddForm ref="attributesAddFormRef" :propertyList="propertyList" />
</template>
<script lang="ts" setup>
// import {PropType, Ref} from 'vue'
// import { copyValueToTarget } from '@/utils'
import { propTypes } from '@/utils/propTypes'
import {
  getPropertyList,
  PropertyAndValues,
  RuleConfig,
  SkuList
} from '@/views/mall/product/spu/components/index'
import ProductAttributes from './ProductAttributes.vue'
import ProductPropertyAddForm from './ProductPropertyAddForm.vue'
import type { Spu } from '@/api/mall/product/spu'
import { priceModeMap, weightUnitMap } from '@/views/dine/config/enums'

defineOptions({ name: 'ProductSpuSkuForm' })

// sku 相关属性校验规则
const ruleConfig: RuleConfig[] = [
  {
    name: 'stock',
    rule: (arg) => arg >= 0,
    message: '产品库存必须大于等于 0 '
  },
  {
    name: 'price',
    rule: (arg) => arg >= 0,
    message: '产品销售价格必须大于等于 0.00 元'
  },
  {
    name: 'costPrice',
    rule: (arg) => arg >= 0,
    message: '产品成本价格必须大于等于 0.00 元'
  },
  {
    name: 'marketPrice',
    rule: (arg) => arg >= 0,
    message: '产品市场价格必须大于等于 0.00 元'
  },
  {
    name: 'wholesalePrice',
    rule: (arg) => arg >= 0,
    message: '产品批发价格必须大于等于 0.00 元'
  },
  {
    name: 'vipPrice',
    rule: (arg) => arg >= 0,
    message: '产品会员价格必须大于等于 0.00 元'
  }
]

const message = useMessage() // 消息弹窗
const formLoading = ref(false)
const props = defineProps({
  // propFormData: {
  //   type: Object as PropType<Spu>,
  //   default: () => {}
  // },
  activeName: propTypes.string.def(''),
  isDetail: propTypes.bool.def(false) // 是否作为详情组件
})
const attributesAddFormRef = ref() // 添加产品规格表单
const formRef = ref() // 表单 Ref
const showBatchSetting = ref(false)
const propertyList = ref<PropertyAndValues[]>([]) // 产品规格列表
const skuListRef = ref() // 产品规格列表 Ref
const formData = defineModel<Spu>({}) // 表单数据
const rules = reactive({
  priceMode: [required],
  specType: [required]
})

// /** 将传进来的值赋值给 formData */
// watch(
//   () => props.propFormData,
//   (data) => {
//     if (!data) {
//       return
//     }
//     copyValueToTarget(formData.value, data)
//     // 将 SKU 的属性，整理成 PropertyAndValues 数组
//     propertyList.value = getPropertyList(data)
//   },
//   {
//     deep: true,
//     immediate: true
//   }
// )
watch(
  () => formData.value,
  (data) => {
    if (!data) {
      return
    }
    // 将 SKU 的属性，整理成 PropertyAndValues 数组
    propertyList.value = getPropertyList(data)
  },
  {
    deep: true,
    immediate: true
  }
)

/** 表单校验 */
const emit = defineEmits(['update:activeName'])
const validate = async () => {
  if (!formRef) return
  try {
    // 校验 sku
    skuListRef.value.validateSku()
    await unref(formRef).validate()
    // // 校验通过更新数据
    // Object.assign(props.propFormData, formData.value)
  } catch (e) {
    message.error('【库存价格】不完善，请填写相关信息')
    emit('update:activeName', 'sku')
    throw e // 目的截断之后的校验
  }
}
defineExpose({ validate })

// /** 是否分佣 */
// const changeBrokerage = () => {
//   // 默认为零，类型切换后也要重置为零
//   for (const item of formData.value.skus!) {
//     item.firstBrokeragePrice = 0
//     item.secondBrokeragePrice = 0
//   }
// }

const onPriceModeChange = (e: any) => {
  if (Number(e) === 2) {
    formData.value!.unitName = weightUnitMap[0]
    formData.value!.stepQuantity = 50
    formData.value!.skus!.forEach((item) => {
      item.weight = formData.value!.stepQuantity! / 1000
    })
  } else {
    formData.value!.unitName = '件'
    formData.value!.stepQuantity = 1
    formData.value!.skus!.forEach((item) => {
      item.weight = 0
    })
  }
}
const onStepQuantityChange = (e: any) => {
  if (Number(formData.value!.priceMode) === 2) {
    formData.value!.skus!.forEach((item) => {
      item.weight = e / 1000
    })
  } else {
    formData.value!.skus!.forEach((item) => {
      item.weight = 0
    })
  }
}

/** 选择规格 */
const onChangeSpec = () => {
  // 重置产品规格列表
  propertyList.value = []
  // 重置sku列表
  formData.value!.skus = [
    {
      price: 0,
      costPrice: 0,
      marketPrice: 0,
      wholesalePrice: 0,
      vipPrice: 0,
      barCode: '',
      picUrl: '',
      stock: 999,
      weight: 0,
      volume: 0,
      firstBrokeragePrice: 0,
      secondBrokeragePrice: 0
    } as any
  ]
}

/** 调用 SkuList generateTableData 方法*/
const generateSkus = (propertyList: any[]) => {
  skuListRef.value?.generateTableData(propertyList)
}

onMounted(() => {
  onChangeSpec()
  // 将 SKU 的属性，整理成 PropertyAndValues 数组
  propertyList.value = getPropertyList(formData.value as Spu)
})
</script>
